package com.jh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jh.constant.MessageConstant;
import com.jh.dto.*;
import com.jh.entity.*;
import com.jh.exception.BaseException;
import com.jh.exception.DeletionNotAllowedException;
import com.jh.mapper.InventoryTransactionDetailMapper;
import com.jh.mapper.InventoryTransactionMapper;
import com.jh.mapper.ProductDetailMapper;
import com.jh.mapper.ProductMapper;
import com.jh.result.PageResult;
import com.jh.service.InventoryService;
import com.jh.vo.InventoryTransactionDetails;
import com.jh.vo.InventoryTransactionVO;
import com.jh.vo.ProductPageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;


@Service
public class InventoryServiceImpl implements InventoryService {
    @Autowired
    private InventoryTransactionMapper inventoryTransactionMapper;
    @Autowired
    private InventoryTransactionDetailMapper inventoryTransactionDetailMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductDetailMapper productDetailMapper;

    /**
     * 商品分页查询
     *
     * @param productPageQueryDTO
     */
    public PageResult page(ProductPageQueryDTO productPageQueryDTO) {
        ProductPageQueryRightDTO productPageQueryRightDTO=new ProductPageQueryRightDTO();
        BeanUtils.copyProperties(productPageQueryDTO,productPageQueryRightDTO);

        String beginTimeString=productPageQueryDTO.getBeginTime();
        if(beginTimeString != null && !beginTimeString.isEmpty()){
            //时间区间不为空的情况
            String endTimeString=productPageQueryDTO.getEndTime();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime beginTime = LocalDateTime.parse(beginTimeString, formatter);
            LocalDateTime endTime = LocalDateTime.parse(endTimeString, formatter);
            productPageQueryRightDTO.setBeginTime(beginTime);
            productPageQueryRightDTO.setEndTime(endTime);
        }

        //开始分页查询
        Page<ProductPageVO> page = new Page<>(productPageQueryDTO.getPage(), productPageQueryDTO.getPageSize());

        page = productMapper.pageQuery(page,productPageQueryRightDTO);

        long total = page.getTotal();
        List<ProductPageVO> records = page.getRecords();

        return new PageResult(total, records);
    }
    /**
     * 商品删除
     * @param ids
     */
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            Product product=productMapper.getByid(id);
            if(product==null){
                throw new DeletionNotAllowedException(MessageConstant.PRODUCT_NOT_FOUND);
            }
            if(product.getInventory()>0){
                throw new DeletionNotAllowedException(MessageConstant.UNKNOWN_ERROR);
            }
        }
        for (Long id : ids) {
            productMapper.deleteByid(id);
        }
    }


    public void update(Product product) {
        productMapper.update(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processInbound(InventoryTransactionSaveDTO dto) {
        processTransaction(dto, true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processOutbound(InventoryTransactionSaveDTO dto) {
        processTransaction(dto, false);
    }

    @Override
    public Boolean check(String skuCode) {
        int count = Math.toIntExact(productDetailMapper.selectCount(
                new LambdaQueryWrapper<ProductDetail>()
                        .eq(ProductDetail::getSkuCode, skuCode)
                        .eq(ProductDetail::getStatus, 1)
        ));
        return count != 0;
    }

    @Override
    public ProductDetail getSkuDetail(String skuCode) {
        // 根据SKU编码查询商品详情
        LambdaQueryWrapper<ProductDetail> queryWrapper = Wrappers.lambdaQuery(ProductDetail.class)
                .eq(ProductDetail::getSkuCode, skuCode)
                .eq(ProductDetail::getStatus, 1);

        return productDetailMapper.selectOne(queryWrapper);
    }

    @Override
    public Page<InventoryTransactionVO> getInventoryTransaction(InventoryTransactionSelectDTO pageQueryDTO) {
        Page<InventoryTransactionVO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<InventoryTransactionVO> pageVO =inventoryTransactionMapper.getInventoryTransaction(page, pageQueryDTO);
        return pageVO;
    }

    @Override
    public List<InventoryTransactionDetails> getInventoryTransactionDetails(Long inventoryTransactionId) {
        List<InventoryTransactionDetails> result = inventoryTransactionMapper.getInventoryTransactionDetails(inventoryTransactionId);
        if (result == null) {
            throw new RuntimeException("出入库单不存在,数据错误");
        }
        return result;
    }

    @Override
    @Transactional
    public void checkInventoryTransaction(Long inventoryTransactionId, Integer status) {
        InventoryTransaction inventoryTransaction = inventoryTransactionMapper.selectById(inventoryTransactionId);
        Integer type = inventoryTransaction.getType();
        switch (status) {
            case 1:
                inventoryTransaction.setStatus(1);
                inventoryTransactionMapper.updateById(inventoryTransaction);
                break;
            case 2:
                List<InventoryTransactionDetail> inventoryTransactionDetails = inventoryTransactionDetailMapper.selectList(
                        new LambdaQueryWrapper<InventoryTransactionDetail>().eq(InventoryTransactionDetail::getTransactionId, inventoryTransactionId));
                switch(type){
                    case 1:
                    //入库的取消就是删掉库存
                    for(InventoryTransactionDetail detail : inventoryTransactionDetails){
                        productDetailMapper.deleteById(detail.getProductDetailId());
                        inventoryTransactionDetailMapper.deleteById(detail.getId());
                    }
                    inventoryTransactionMapper.deleteById(inventoryTransactionId);
                    break;
                    case 2:
                    //出库的取消就是加回库存
                        for(InventoryTransactionDetail detail : inventoryTransactionDetails){
                            ProductDetail productDetail = productDetailMapper.selectById(detail.getProductDetailId());
                            productDetail.setStatus(1);
                            productDetailMapper.updateById(productDetail);
                            inventoryTransaction.setStatus(2);
                            inventoryTransactionMapper.updateById(inventoryTransaction);
                        }
                        break;
                    default:
                        throw new BaseException("未知操作类型");
                }
                break;
            default:
                throw new BaseException("未知操作类型");
        }
    }


    private void processTransaction(InventoryTransactionSaveDTO dto, boolean isInbound) {
        List<InventoryTransactionDetailIn> details = dto.getDetails();
        if (details == null || details.isEmpty()) {
            throw new IllegalArgumentException(isInbound ? "入库商品不能为空" : "出库商品不能为空");
        }

        // 保存库存交易
        InventoryTransaction transaction = InventoryTransaction.builder()
                .type(dto.getType())
                .transactionCode(dto.getTransactionCode())
                .source(dto.getSource())
                .remark(dto.getRemark())
                .build();
        inventoryTransactionMapper.insert(transaction);

        for (InventoryTransactionDetailIn detail : details) {
            // 查询或创建产品
            LambdaQueryWrapper<Product> productQuery = Wrappers.lambdaQuery(Product.class)
                    .eq(StringUtils.hasText(detail.getBrand()), Product::getBrand, detail.getBrand())
                    .eq(StringUtils.hasText(detail.getProductCode()), Product::getProductCode, detail.getProductCode())
                    .eq(StringUtils.hasText(detail.getColor()), Product::getColor, detail.getColor());

            Product product = Optional.ofNullable(productMapper.selectList(productQuery))
                    .flatMap(products -> products.stream().findFirst())
                    .orElseGet(() -> {
                        if (!isInbound) {
                            throw new RuntimeException("未找到匹配的商品信息");
                        }
                        Product newProduct = Product.builder()
                                .brand(detail.getBrand())
                                .productCode(detail.getProductCode())
                                .color(detail.getColor())
                                .retailPrice(detail.getRetailPrice())
                                .build();
                        productMapper.insert(newProduct);
                        return newProduct;
                    });

            // 查询或创建产品详情
            LambdaQueryWrapper<ProductDetail> detailQuery = Wrappers.lambdaQuery(ProductDetail.class)
                    .eq(ProductDetail::getProductId, product.getId())
                    .eq(ProductDetail::getSkuCode, detail.getSkuCode())
                    .eq(ProductDetail::getSizeType, detail.getSizeType());

            ProductDetail productDetail = isInbound
                    ? Optional.ofNullable(productDetailMapper.selectOne(detailQuery))
                    .orElseGet(() -> {
                        ProductDetail newDetail = ProductDetail.builder()
                                .productId(product.getId())
                                .skuCode(detail.getSkuCode())
                                .sizeType(detail.getSizeType())
                                .build();
                        productDetailMapper.insert(newDetail);
                        return newDetail;
                    })
                    : Optional.ofNullable(productDetailMapper.selectOne(detailQuery))
                    .orElseThrow(() -> new RuntimeException("未找到匹配的商品详情（SKU + 尺码）"));

            // 保存库存交易详情
            InventoryTransactionDetail transactionDetail = InventoryTransactionDetail.builder()
                    .transactionId(transaction.getId())
                    .productDetailId(productDetail.getId())
                    .build();
            inventoryTransactionDetailMapper.insert(transactionDetail);
        }
    }



}
